package com.yztc.yidoutang.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.yztc.yidoutang.bean.SearchHistoryBean;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by My on 2016/10/19.
 */

public class DBHelper {
    public static void  storeSearchHistory(String text, MySqliteOpenHelper helper, Context context){
        if (!TextUtils.isEmpty(text)){
            int count=0;
            try {
                SearchHistoryBean historyBean=new SearchHistoryBean(text);
                count=helper.getSearchHistoryDao().create(historyBean);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (count>0){
                Log.i("db","Success");
            }else {
                Log.i("db","Failed");
            }
        }else {
            Toast.makeText(context,"请输入关键字",Toast.LENGTH_SHORT).show();
        }
    }

    //查询数据库表中所有数据
    public static List<SearchHistoryBean> selectAll(MySqliteOpenHelper helper){
        try {
            Dao<SearchHistoryBean, Integer> searchHistoryDao=helper.getSearchHistoryDao();
            searchHistoryDao.queryBuilder().orderBy("_id",true);
            return searchHistoryDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //查询单条数据
    public static List<SearchHistoryBean> queryOne(MySqliteOpenHelper helper,String queryText,Context context){
        Dao<SearchHistoryBean, Integer> searchHistoryDao=helper.getSearchHistoryDao();
        QueryBuilder<SearchHistoryBean, Integer> builder=searchHistoryDao.queryBuilder();
        if (TextUtils.isEmpty(queryText)){
            Toast.makeText(context,"请输入关键字",Toast.LENGTH_SHORT).show();
        }else {
            try {
                builder.orderBy("_id",true).where().eq("querytext",queryText);
                List<SearchHistoryBean> result=builder.query();
                return result;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
